import React, { memo, useCallback, useEffect, useState } from 'react';
import { View, Text, StyleSheet, TouchableOpacity, Linking, Platform, Alert, FlatList } from 'react-native';
import Icon from 'react-native-vector-icons/MaterialIcons';
import Geolocation from '@react-native-community/geolocation';

interface Hospital {
  id: string;
  name: string;
  address: string;
  distance: number;
  phone: string;
  businessHours: string;
  location: {
    latitude: number;
    longitude: number;
  };
}

// 添加计算距离的辅助函数
const calculateDistance = (lat1: number, lon1: number, lat2: number, lon2: number): number => {
  const R = 6371e3; // 地球半径（米）
  const φ1 = lat1 * Math.PI/180;
  const φ2 = lat2 * Math.PI/180;
  const Δφ = (lat2-lat1) * Math.PI/180;
  const Δλ = (lon2-lon1) * Math.PI/180;

  const a = Math.sin(Δφ/2) * Math.sin(Δφ/2) +
          Math.cos(φ1) * Math.cos(φ2) *
          Math.sin(Δλ/2) * Math.sin(Δλ/2);
  const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));

  return R * c; // 返回米数
};

interface NearbyHospitalsProps {
  hospitals: Hospital[];
  onNavigate: (latitude: number, longitude: number) => void;
}

// 单独封装每个医院卡片，减少无谓的重渲染
const HospitalCard = memo(({ hospital, onNavigate, onCall }: {
  hospital: Hospital;
  onNavigate: (lat: number, lng: number) => void;
  onCall: (phone: string) => void;
}) => {
  const [userLocation, setUserLocation] = useState<{latitude: number; longitude: number} | null>(null);
  const [realDistance, setRealDistance] = useState<number>(hospital.distance);

  // 获取用户位置并计算实际距离
  useEffect(() => {
    Geolocation.getCurrentPosition(
      (position) => {
        const { latitude, longitude } = position.coords;
        setUserLocation({ latitude, longitude });
        
        // 计算实际距离
        const distance = calculateDistance(
          latitude,
          longitude,
          hospital.location.latitude,
          hospital.location.longitude
        ) / 1000; // 转换为公里
        
        setRealDistance(Number(distance.toFixed(1)));
      },
      (error) => {
        console.log('获取位置失败，使用API返回的距离', error);
        setRealDistance(hospital.distance);
      },
      {
        enableHighAccuracy: true,
        timeout: 15000,
        maximumAge: 10000
      }
    );
  }, [hospital.location]);

  const handleNavigate = useCallback(() => {
    if (!hospital.location.latitude || !hospital.location.longitude) {
      Alert.alert('导航错误', '该医院位置信息不完整，无法导航');
      return;
    }
    onNavigate(hospital.location.latitude, hospital.location.longitude);
  }, [hospital.location, onNavigate]);

  const handleCall = useCallback(() => {
    onCall(hospital.phone);
  }, [hospital.phone, onCall]);

  return (
    <View style={styles.hospitalCard}>
      <Text style={styles.hospitalName}>{hospital.name}</Text>
      <Text style={styles.infoText}>地址：{hospital.address}</Text>
      <Text style={styles.infoText}>电话：{hospital.phone}</Text>
      <Text style={styles.infoText}>营业时间：{hospital.businessHours}</Text>
      <View style={styles.distanceWrapper}>
        <Icon name="location-on" size={16} color="#666" />
        <Text style={styles.distanceText}>{realDistance}KM</Text>
      </View>
      <View style={styles.actions}>
        <TouchableOpacity
          style={[styles.button, styles.callButton]}
          onPress={handleCall}
        >
          <Icon name="add" size={20} color="#fff" />
          <Text style={styles.buttonText}>去挂号</Text>
        </TouchableOpacity>
        <TouchableOpacity
          style={[styles.button, styles.navigationButton]}
          onPress={handleNavigate}
        >
          <Icon name="navigation" size={20} color="#fff" />
          <Text style={styles.buttonText}>导航前往</Text>
        </TouchableOpacity>
      </View>
    </View>
  );
});

// 主列表组件
const NearbyHospitals: React.FC<NearbyHospitalsProps> = memo(({ hospitals, onNavigate }) => {
  const handleCall = useCallback((phone: string) => {
    if (!phone || phone === '电话未提供') {
      Alert.alert('提示', '该医院未提供电话信息');
      return;
    }
    try {
      Linking.openURL(`tel:${phone}`);
    } catch (error) {
      console.error('拨打电话失败:', error);
      Alert.alert('错误', '无法拨打电话，请手动拨打');
    }
  }, []);

  if (hospitals.length === 0) {
    return (
      <View style={styles.emptyContainer}>
        <Text style={styles.emptyText}>暂无医院数据</Text>
      </View>
    );
  }

  return (
    <>
      <View style={styles.headerContainer}>
        <Text style={styles.title}>
          您附近有{hospitals.length}家医院
        </Text>
        {/* <View style={styles.headerLine} /> */}
      </View>
      <FlatList
        data={hospitals}
        renderItem={({ item }) => (
          <HospitalCard
            hospital={item}
            onNavigate={onNavigate}
            onCall={handleCall}
          />
        )}
        keyExtractor={item => item.id}
        contentContainerStyle={styles.container}
        showsVerticalScrollIndicator={false}
      />
    </>
  );
});

const styles = StyleSheet.create({
  container: {
    backgroundColor: '#f6f6f6',
  },
  headerContainer: {
    paddingTop: 12,
    paddingBottom: 0,
    backgroundColor: '#f6f6f6',
  },
  title: {
    fontSize: 14,
    color: '#666',
    paddingHorizontal: 16,
    // paddingBottom: 12,
    // backgroundColor: '#fff',
    lineHeight: 40,
    marginTop: -10
  },
  headerLine: {
    height: 1,
    backgroundColor: '#1677ff',
    width: '100%',
  },
  hospitalCard: {
    backgroundColor: '#fff',
    paddingVertical: 16,
    paddingHorizontal: 16,
    borderBottomWidth: StyleSheet.hairlineWidth,
    borderBottomColor: '#F7F8FA 100%',
    margin: 20,
    borderRadius: 8,
    elevation: 1,
    shadowColor: '#000',
    shadowOffset: {
      width: 0,
      height: 1,
    },
    shadowOpacity: 0.1,
    shadowRadius: 2,
  },
  hospitalName: {
    fontSize: 16,
    color: '#333',
    marginBottom: 8,
  },
  infoText: {
    fontSize: 14,
    color: '#666',
    marginBottom: 4,
  },
  distanceWrapper: {
    position: 'absolute',
    right: 16,
    bottom:75,
    // top: 16,
    flexDirection: 'row',
    alignItems: 'center',
  },
  distanceText: {
    fontSize: 14,
    color: '#666',
    marginLeft: 4,
  },
  actions: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    marginTop: 12,
    gap: 12,
  },
  button: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    paddingVertical: 8,
    paddingHorizontal: 0,
    borderRadius: 43,
    flex: 1,
  },
  callButton: {
    backgroundColor: '#1677ff',
  },
  navigationButton: {
    backgroundColor: '#1677ff',
  },
  buttonText: {
    color: '#fff',
    fontSize: 14,
    marginLeft: 4,

    // borderRadius: 43,
},
  emptyContainer: {
  padding: 16,
  alignItems: 'center',
  justifyContent: 'center',
  height: 100,
  backgroundColor: '#fff',
},
  emptyText: {
  fontSize: 14,
  color: '#666',
},
});

export default NearbyHospitals; 